package com.usooft.metaTalent.core.system.service.base;

import com.usooft.framework.core.query.Limit;
import com.usooft.framework.core.query.Page;
import com.usooft.metaTalent.core.system.entity.Role;
import com.usooft.metaTalent.core.system.mapper.RoleMapper;
import com.usooft.metaTalent.core.system.query.RoleQuery;
import com.usooft.metaTalent.core.system.service.RoleService;
import com.usooft.metaTalent.core.system.wrapper.RoleWrapper;
import java.lang.Long;
import java.lang.Override;
import java.lang.String;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.lang.NonNull;

public abstract class BaseRoleService implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Role get(@NonNull Long id) {
        return find(id).orElseThrow();
    }

    @Override
    public Optional<Role> find(@NonNull Long id) {
        return Optional.ofNullable(roleMapper.get(id));
    }

    @Override
    public List<RoleWrapper> list(RoleQuery query) {
        return roleMapper.list(query);
    }

    @Override
    public Page<RoleWrapper> page(RoleQuery query) {
        int rows = roleMapper.count(query.getFilter());
        return new Page<>(rows, rows == 0 ? new ArrayList<>() : roleMapper.list(query));
    }

    protected Optional<Role> findOne(RoleQuery.Filter filter, RoleQuery.Sorts sorts) {
        List<RoleWrapper> wrappers = list(RoleQuery.builder()
                                .filter(filter)
                                .sorts(sorts)
                                .limit(Limit.rowCount(1))
                                .build());
        return wrappers.stream().findFirst().map(Function.identity());
    }

    protected Optional<Role> findOne(RoleQuery.Filter filter) {
        return findOne(filter, RoleQuery.Sorts.builder().build());
    }

    @Override
    public int count(RoleQuery.Filter filter) {
        return roleMapper.count(filter);
    }

    protected Role internalAdd(String name, String description) {
        Role role = new Role();
        role.setName(name);
        role.setDescription(description);

        role.setCreatedDate(LocalDateTime.now());
        role.setVersion(0);
        role.setLocked(false);
        roleMapper.add(role);
        return role;
    }

    protected void internalUpdate(@NonNull Role role) {
        role.setLastModifiedDate(LocalDateTime.now());

        int rows = roleMapper.update(role);
        if (rows == 0) {
            throw new OptimisticLockingFailureException("更新失败。可能角色 (" + role.getId() + ") 的版本 (" + role.getVersion() + ") 已不是最新");
        }
        role.setVersion(role.getVersion() + 1);
    }
}
